package net.thxjj.mobileServer.websocket;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import net.thxjj.mobileServer.entity.AppLoginBean;
import net.thxjj.mobileServer.entity.AppRespBean;
import net.thxjj.mobileServer.entity.GenieResum;
import net.thxjj.mobileServer.service.IUserService;
import net.thxjj.mobileServer.util.ParameterMap;
import net.thxjj.mobileServer.util.Tools;
import org.apache.commons.lang.StringUtils;

import java.util.logging.Logger;

public class AppLoginHandler extends HeartBeatBaseChannelInBoundHandler{
    private Logger log = Logger.getLogger(String.valueOf(this.getClass()));


    @Override
    public void chanelReadR(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        if(!AppSocketMap.hasUser(ctx.channel())){


            String de = msg.text();
            AppLoginBean loginBean =  JSONObject.parseObject(de, AppLoginBean.class);

            //判断access_token是否为空
            String access_token = loginBean.getParams().getToken();
            if(Tools.isEmpty(access_token)){
                AppRespBean appRespBean =  new AppRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.JWT_EMPTY_ERROR.getCode(),ErrCode.JWT_EMPTY_ERROR.getDescription());
                ctx.writeAndFlush(new TextWebSocketFrame(appRespBean.toString()));
                ctx.close();
                return;
            }

            //判断appTid是否为空
            String appTid = loginBean.getParams().getAppTid();
            if(Tools.isEmpty(appTid)){
                AppRespBean appRespBean =  new AppRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.APPTID_EMPTY_ERROR.getCode(),ErrCode.APPTID_EMPTY_ERROR.getDescription());
                ctx.writeAndFlush(new TextWebSocketFrame(appRespBean.toString()));
                ctx.close();
                return;
            }


            //JWT验证失败，即不存在
            ParameterMap parameterMap = userService.getUserSnapshot(access_token);
            if(parameterMap==null){
                AppRespBean appRespBean =  new AppRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.JWT_NOT_EXIST_ERROR.getCode(),ErrCode.JWT_NOT_EXIST_ERROR.getDescription());
                ctx.writeAndFlush(new TextWebSocketFrame(appRespBean.toString()));
                ctx.close();
                return;
            }

            String app_tid = parameterMap.getString("app_tid");
            if(!appTid.contains(app_tid)){
                AppRespBean appRespBean =  new AppRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.APPTID_CHECK_ERROR.getCode(),ErrCode.APPTID_CHECK_ERROR.getDescription());
                ctx.writeAndFlush(new TextWebSocketFrame(appRespBean.toString()));
                ctx.close();
                return;

            }

            //JWT有效期超时，即jwt过期
            long time_re =  Integer.parseInt(parameterMap.getString("refresh_time"));
            if(time_re+ GenieResum.ACCESS_TOKEN_EXPIRED_SECOND <System.currentTimeMillis()){
                AppRespBean appRespBean =  new AppRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.JWT_TIME_OUT_ERROR.getCode(),ErrCode.JWT_TIME_OUT_ERROR.getDescription());
                ctx.writeAndFlush(new TextWebSocketFrame(appRespBean.toString()));
                ctx.close();
                return;
            }

            AppSocketMap.addUser(ctx.channel(),access_token);

            AppRespBean appRespBean =  new AppRespBean(loginBean.getMsgId(), ActionType.APP_LOGINRESP.getName(), ErrCode.SUCCESS.getCode(),ErrCode.SUCCESS.getDescription());
            ctx.writeAndFlush(new TextWebSocketFrame(appRespBean.toString()));
        }else{
            ctx.close();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
        super.channelRead0(channelHandlerContext,msg);

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
}
